/**
 * 生成gruntfile配置
 * 1.选出>=300k的图片 手动写到配置内 （待确定是否会导致配置文件过大
 * 2.选出>=300k的图片 复制到另一目录内 配置内使用该目录 执行完压缩后覆盖回去（
 */
let fs = require('fs');
let path = require("path");
let exec = require('child_process').exec;
let readline = require('readline');
var pngquant = require('node-pngquant-native');

// fs.readFile('./alphatest.png', function (err, buffer) {
//   if (err) throw err;
//   var resBuffer = pngquant.compress(buffer, {
//     "speed": 1 //1 ~ 11
//   });

//   fs.writeFile('./alphatest_out.png', resBuffer, {
//       flags: 'wb'
//   }, function(err){});
// });

let rl = readline.createInterface({
    input: process.stdin,
    output: process.stdout
});
let limitSize = 300;

let tempDir = `tmp`;
let largeFiles = [];
let backFileAmount = 0;
let srcDir;
let options = process.argv;
let baseName;

// /Users/xyxy/Documents/WORKS/legendClient/legendClient/assets/resources
if (options[2]) {
    srcDir = options[2];
    baseName = path.basename(srcDir);;
    //开始
    startMin();
} else {
    rl.question('输入resources路径（或直接拖入resource/目录到控制台）', (src) => {
        // TODO: Log the answer in a database
        srcDir = src.trim();
        baseName = path.basename(srcDir);;
        console.log('baseName ', baseName);

        startMin();
        rl.close();
    });
}

function startMin() {
    readDir(srcDir);
}
function readDir(src) {
    let s = fs.statSync(src);
    if(!s.isDirectory()){
        compressFile(src);
        return;
    }
    let dir = fs.readdirSync(src);
    dir.forEach(d => {
        let stat = fs.statSync(src + '/' + d);
        if (stat.isDirectory()) {
            readDir(src + '/' + d);
        } else if (path.extname(src + '/' + d) == '.png' || path.extname(src + '/' + d) == '.jpg') {
            if (stat.size >= limitSize * 1000) {
                console.log('大于300K ', d);
                largeFiles.push({
                    src: src + '/' + d,
                    size: stat.size,
                    name: d
                });
                //直接使用pngquant处理
                compressFile(src+'/'+d);
            }
        } else {
        }
    });
}
function compressFile(src){
    console.log('开始压缩 请等待覆盖完成 ', src);
    fs.readFile(src, function (err, buffer) {
        if (err) throw err;
        var resBuffer = pngquant.compress(buffer, {
            "speed": 1 //1 ~ 11
        });

        fs.writeFile(src, resBuffer, {
            flags: 'w'
        }, function (err) {
            console.log('覆盖完成',src);
         });
    });
}